package cn.lysoy.demo.utils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件压缩工具封装
 * @author SongYang
 */
public class ZipUtils {
    public static File zipFile(File src) throws IOException{
        File zipFile = new File(FileUtil.getFileNameNoEx(src.getAbsolutePath())+".zip");
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
        ZipEntry entry = new ZipEntry( src.getName());
        zos.putNextEntry(entry);
        int count;
        byte[] buf = new byte[1024];
        while ((count = bis.read(buf)) != -1) {
            zos.write(buf, 0, count);
        }
        bis.close();
        //fos.close();
        zos.close();//
        return zipFile;
    }

    public static File zipTempFile(File src) throws IOException{
        File zipFile = File.createTempFile(FileUtil.getFileNameNoEx(src.getAbsolutePath()), ".zip");
        zipFile.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
        ZipEntry entry = new ZipEntry( src.getName());
        zos.putNextEntry(entry);
        int count;
        byte[] buf = new byte[1024];
        while ((count = bis.read(buf)) != -1) {
            zos.write(buf, 0, count);
        }
        bis.close();
        //fos.close();
        zos.close();//
        return zipFile;
    }
}
